﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using OfficeOpenXml;
using QDWK.Class;
using QDWK.Scheduler;
using Quartz;
using Quartz.Impl;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using WFDAR;

namespace QDWK
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} 系统启动");
            IConfiguration configuration = null;
            var builder = Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
            {
                // 注册 NLog
                services.AddLogging(loggingBuilder =>
                {
                    loggingBuilder.ClearProviders();
                    loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
                    loggingBuilder.AddNLog();
                });

                services.AddQuartz(q =>
                {
                    var scheduleConfig = context.Configuration.GetSection("Schedule").Get<ScheduleConfig>();
                    
                    // 为每个表达式创建任务
                    foreach (var cron in scheduleConfig.CronExpressions)
                    {
                        var jobKey = new JobKey($"DataQueryJob_{cron}", "Group1");
                        q.AddJob<DataQueryJob>(j => j.WithIdentity(jobKey));

                        q.AddTrigger(t => t
                            .WithIdentity($"Trigger_{cron}", "Group1")
                            .ForJob(jobKey)
                            .WithCronSchedule(cron)
                        );
                    }

                    var jobKey2 = new JobKey($"DataQueryJob", "Group1");
                    q.AddJob<DataQueryJob>(j => j.WithIdentity(jobKey2));
                    // 新增立即执行的单次触发器
                    q.AddTrigger(t => t
                        .WithIdentity($"ImmediateTrigger", "Group1")
                        .ForJob(jobKey2)
                        .StartNow() // 启动后立即触发
                        .WithSimpleSchedule(s => s
                                .WithRepeatCount(0) // 仅执行一次
                                .WithMisfireHandlingInstructionFireNow() // 处理可能的延迟
                        )
                    );
                });

                // 添加 Quartz 后台服务
                services.AddQuartzHostedService(q =>
                    q.WaitForJobsToComplete = true);
           

                //services.AddSingleton<StdSchedulerFactory>();
                var sysInfo = context.Configuration.GetSection("SysInfo").Get<SysInfo>();
                services.AddSingleton(sysInfo);

                var remoteSysInfo = context.Configuration.GetSection("RemoteSysInfo").Get<RemoteSysInfo>();
                services.AddSingleton(remoteSysInfo);

                //services.AddSqlSugar(context.Configuration);
                services.AddScoped<CZjzy>();
                services.AddHttpClient();
                services.AddSingleton<CQdwk>();
                configuration = context.Configuration;

                services.AddTransient<DataQueryJob>();
            });

            var host = builder.Build();

            string baseDir = AppContext.BaseDirectory;
            string newDirPath = Path.Combine(baseDir, "MesHistoryData");
            if (!Directory.Exists(newDirPath))
            {
                try
                {
                    // 创建目录（自动创建所有层级）
                    Directory.CreateDirectory(newDirPath);
                    Console.WriteLine($"目录已创建: {newDirPath}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"创建目录失败: {ex.Message}");
                }
            }

            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} 系统启动完成，等待任务执行！");
            await host.RunAsync();
        }
    }
}
